import Login from '../pages/login/index';
import Layout from '../pages/layout/index';
import Home from '../pages/home/index';
import Table from '../pages/table/index';
import NotPage from '../pages/404/index';
import { useRoutes, Navigate, RouteObject } from 'react-router-dom';
import React from 'react';

function getItem(
  path: RouteObject['path'],
  element: RouteObject['element'],
  children?: RouteObject['children']
): RouteObject {
  return {
    path,
    element,
    children
  } as RouteObject;
}

const routers: RouteObject[] = [
  getItem('/login', <Login></Login>),
  getItem('/', <Layout></Layout>, [
    getItem('/', <Home></Home>),
    getItem('/table', <Table></Table>)
  ]),
  getItem('*', <NotPage></NotPage>)
];

const isUserAuthenticated = () => {
  const token = localStorage.getItem('token');
  return token && token.length > 0;
};

const AuthRoute: React.FC<React.PropsWithChildren> = (props: React.PropsWithChildren) => {
  if (!isUserAuthenticated()) {
    return (
      <div>
        {props.children}
        <Navigate to="/login" />
      </div>
    );
  }
  return <div>{props.children}</div>;
};
AuthRoute.displayName = 'AuthRoute';

const RouterInterceptor: React.FC = (props: React.PropsWithChildren) => {
  const routerEls = useRoutes(routers);
  return <AuthRoute>{routerEls}</AuthRoute>;
};
RouterInterceptor.displayName = 'RouterInterceptor';
export default RouterInterceptor;
